package com.demo.springcloud.lb;


import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;
import sun.nio.ch.Net;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chenyuan
 * @date 2020/12/3 12:40
 */
@Component
public class MyLB implements LoadBalancer {

	// 用于统计当前的访问次数
	private AtomicInteger atomicInteger = new AtomicInteger(0);

	/**
	 * @return 当前是第几次访问
	 */
	public final int getAndIncrement() {
		int current, next;
		// 自旋锁
		do {
			current = this.atomicInteger.get();
			next = current >= 2147483647 ? 0 : current + 1;
		} while (!this.atomicInteger.compareAndSet(current, next));
		System.out.println("【 当前访问次数 】 next = :" + next);
		return next;
	}

	@Override
	public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
		// 通过取余，计算出当前应该是哪一个 Provider 提供服务
		int index = getAndIncrement() % serviceInstances.size();
		ServiceInstance instance = serviceInstances.get(index);
		System.out.println("当前是 【" + instance.getUri() + "】 提供服务");
		return instance;
	}
}
